package com.ceba.be.api.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64FileUtils {
	/**
	 * 将文件内容base64编码
	 * 
	 * @param path 文件路径
	 * @return String base64编码过的文件内容
	 * @throws Exception
	 */

	public static String encodeBase64File(String path) throws Exception {
		File file = new File(path);
		FileInputStream inputFile = new FileInputStream(file);
		byte[] buffer = new byte[(int) file.length()];
		inputFile.read(buffer);
		inputFile.close();
		return new BASE64Encoder().encode(buffer);

	}

	/**
	 * 解码base64字符串，并写入本地磁盘
	 * 
	 * @param base64Code
	 * @param targetPath
	 * @throws Exception
	 */

	public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
		byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
		FileOutputStream out = new FileOutputStream(targetPath);
		out.write(buffer);
		out.close();

	}

	/**
	 * 将文件内容写入磁盘
	 * 
	 * @param contents
	 * @param targetPath
	 * @throws Exception
	 */

	public static void toFile(String contents, String targetPath) throws Exception {

		byte[] buffer = contents.getBytes();
		FileOutputStream out = new FileOutputStream(targetPath);
		out.write(buffer);
		out.close();
	}

	public static void main(String[] args) {
		try {
			String base64Code = encodeBase64File("e://test/1.pdf");
			System.out.println(URLEncoder.encode(base64Code,"UTF-8"));
//			decoderBase64File(base64Code, "e://test/1---1.pdf");
//			toFile(base64Code, "e://test/three.txt");
		} catch (Exception e) {
			e.printStackTrace();

		}

	}
}